package com.cardbaobao.cardbabyclient.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.controller.Controller;
import com.cardbaobao.cardbabyclient.model.QuickDebitFeeRateData;
import com.cardbaobao.cardbabyclient.model.QuickDebitOrder;
import com.cardbaobao.cardbabyclient.model.RealName;
import com.cardbaobao.cardbabyclient.model.UserBindCards;
import com.cardbaobao.cardbabyclient.model.result.HasBindCardResult;
import com.cardbaobao.cardbabyclient.model.result.QuickDebitOrderResult;
import com.cardbaobao.cardbabyclient.model.result.UserBindCardsResult;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.adapter.CreditLimitQuotaAdapter;
import com.cardbaobao.cardbabyclient.ui.dialog.NormalDialog;
import com.cardbaobao.cardbabyclient.ui.helper.DebitHelper;
import com.cardbaobao.cardbabyclient.ui.pop.ListPop;
import com.cardbaobao.cardbabyclient.ui.pop.NumberKeyBoardPop;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import rx.Subscriber;

/**
 * Created by Jiangzx on 2017/9/4 16:07.
 * 快捷收款
 */

public class QuickDebitActivity extends BaseActivity {
    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.et_amount)
    EditText etAmount;
    @BindView(R.id.ibt_delete)
    ImageButton ibtDelete;
    @BindView(R.id.ll_pre_view)
    LinearLayout llPreView;
    @BindView(R.id.tv_fee)
    TextView tvFee;
    @BindView(R.id.tv_amount_money)
    TextView tvAmountMoney;

    @BindView(R.id.tv_union_des)
    TextView tvUnionDes;
    @BindView(R.id.tv_rate)
    TextView tvRate;
    @BindView(R.id.tv_settlement)
    TextView tvSettlement;
    @BindView(R.id.tv_quota)
    TextView tvQuota;

    private ArrayList<QuickDebitFeeRateData.FeeRate> rates;
    private QuickDebitFeeRateData.FeeRate rate;//获取费率(银联)
    @Override
    protected int getLayoutId() {
        return R.layout.activity_quick_debit;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        ImmersionBar.with(this).statusBarDarkFont(true,Constant.STATUS_BAR_FONT_ALPHA).init();
        //处理输入框光标
        try{
            Class<EditText> cls = EditText.class;
            Method setShowSoftInputOnFocus;
            setShowSoftInputOnFocus = cls.getMethod(
                    "setShowSoftInputOnFocus", boolean.class);
            setShowSoftInputOnFocus.setAccessible(true);
            setShowSoftInputOnFocus.invoke(etAmount, false);
        }catch (Exception e){
            e.printStackTrace();
        }
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        resetPreViewUi();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mCurrentPageId=Self.Page.app_quick_cashier;
        titleBar.setRightViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //埋点
                SelfUtils.buriedClickData(Self.Action.app_click_quick_cashier_common_problem,
                        Self.Action.app_click_quick_cashier_common_problem_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);

                Controller controller=new Controller(mContext);
                controller.toCommonQuestion(QuickDebitActivity.this,mCurrentPageId);
            }
        });
        //获取收款费率
        rates=getIntent().getParcelableArrayListExtra(FeeRateActivity.QUICK_DEBIT_FEE_RATE_LIST_ARRAY);
        for(QuickDebitFeeRateData.FeeRate r:rates){
            if(Constant.KQB010101.equals(r.getChannel_type())){
                rate=r;
                tvUnionDes.setText(rate.getChannel_name());
                tvRate.setText(
                        String.format(Locale.CHINESE,
                                Constant.AMOUNT_FORMAT,
                                Double.parseDouble(rate.getRate())) +"%");
                tvSettlement.setText(
                        String.format(Locale.CHINESE,
                                Constant.AMOUNT_FORMAT,
                                Double.parseDouble(rate.getEach_charge()))+ "元/笔");
                //判断是否为整数
                try{
                    //转成整数
                    long amount=Long.parseLong(rate.getHigh_position());
                    if(amount>=10000){
                        if(amount%10000==0){
                            tvQuota.setText("当天"+(amount/10000)+"万元");
                        }else{
                            tvQuota.setText("当天"+ String.format(Locale.CHINESE, Constant.AMOUNT_FORMAT,amount/10000.0)
                                            +"万元");
                        }
                    }else{
                        tvQuota.setText("当天"+amount+"元");
                    }
                }catch (Exception e){
                    //转成小数
                    tvQuota.setText("当天"+
                                    String.format(Locale.CHINESE,Constant.AMOUNT_FORMAT,Double.parseDouble(rate.getHigh_position()))+
                                    "元");
                }
                break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        final Dialog normalDialog=new NormalDialog(this).
                setButtonListener(new NormalDialog.ButtonListener() {
                    @Override
                    public void onLeftBtClicked(NormalDialog dialog) {
                        dialog.dismiss();
                    }

                    @Override
                    public void onRightBtClicked(NormalDialog dialog) {
                        dialog.dismiss();
                        finish();
                    }
                });
        //判断，如果时间不是位于7:00~22:50时，弹出对话框
        Calendar calendar=new GregorianCalendar(Locale.CHINESE);
        calendar.setTimeInMillis(System.currentTimeMillis());
        int hour=calendar.get(Calendar.HOUR_OF_DAY);
        if(hour<7||hour>22){
            normalDialog.show();
        }else{
            if(hour==22&&calendar.get(Calendar.MINUTE)>=50){
                normalDialog.show();
            }
        }
        GoogleAnalyticsUtil.setScreenName("快捷收款");
    }

    //获取信用卡列表
    private void loadCreditCards(){
        Api.getUserBindCards(String.valueOf(mApplication.getUser().getID())).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable throwable) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                                getString(R.string.string_request_data_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        UserBindCardsResult result=JsonUtil.json2Object(s,UserBindCardsResult.class);
                        if(result.getCode()==Constant.SUC_CODE){
                            UserBindCards cards=result.getData();
                            if(cards!=null){
                                List<CreditLimitQuotaAdapter.TypeCreditCard> typeDataList=
                                        new ArrayList<>();
                                List<UserBindCards.CreditCard> creditCards=cards.getCreditCardList();
                                if(creditCards!=null&&creditCards.size()>0){
                                    //获取用户绑定的信用卡成功
                                    for(int i=0,size=creditCards.size();i<size;i++){
                                        typeDataList.add(new CreditLimitQuotaAdapter.TypeCreditCard(CreditLimitQuotaAdapter.TYPE_ITEM_NORMAL,
                                                creditCards.get(i)));
                                    }
                                    typeDataList.add(new CreditLimitQuotaAdapter.TypeCreditCard(CreditLimitQuotaAdapter.TYPE_ADD_CARD,null));
                                    showChooseCardPop(typeDataList);
                                }
                            }
                        }else{
                            ToastUtil.showToast(result.getMsg());
                        }
                    }
                });
    }

    private void resetPreViewUi(){
        tvFee.setText("0.00元");
        tvAmountMoney.setText("0.00元");
    }

    @OnTextChanged(R.id.et_amount)
    public void onTextChanged(CharSequence s, int start, int before, int count){
        if(s.length()>0){
            ibtDelete.setVisibility(View.VISIBLE);
        }else{
            ibtDelete.setVisibility(View.INVISIBLE);
            resetPreViewUi();
        }
    }

    private void checkBindCreditCard(String amount){
        showProgressDialog(false);
        Api.hasBindCreditCard(String.valueOf(mApplication.getUser().getID()),
                amount).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                HasBindCardResult result=JsonUtil.json2Object(s,HasBindCardResult.class);
                if(result.getCode()==Constant.SUC_CODE){
                    RealName realName=result.getData();
                    if(!TextUtils.isEmpty(realName.getTrue_name())&&!TextUtils.isEmpty(realName.getId_card_no())){
                        //未绑定信用卡，去绑定信用卡
                        dismissProgressDialog();
                        //埋点
                        SelfUtils.buriedClickData(Self.Action.app_click_no_credit_cards_added_goadd,
                                Self.Action.app_click_no_credit_cards_added_goadd_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);

                        Intent intent=new Intent(mContext,AddCreditCardPreActivity.class);
                        intent.putExtra(AddCreditCardActivity.NAME_S,realName.getTrue_name());
                        intent.putExtra(AddCreditCardActivity.ID_CARD_NO_S,realName.getId_card_no());
                        intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(intent);
                    }else{
                        //获取信用卡列表
                        loadCreditCards();
                    }
                }else{
                    //失败
                    dismissProgressDialog();
                    ToastUtil.showToast(result.getMsg());
                }
            }
        });
    }

    private NumberKeyBoardPop pop;
    StringBuilder sb;
    private void showPopKeyboard(){
        if(pop==null){
            pop=new NumberKeyBoardPop(mContext);
            pop.setNumberKeyListener(new NumberKeyBoardPop.OnKeyPressed() {
                @Override
                public void onKeyPressed(int key) {
                    if(sb==null){
                        sb=new StringBuilder();
                    }else{
                        sb.delete(0,sb.length());
                    }
                    sb.append(etAmount.getText().toString());
                    switch (key){
                        case NumberKeyBoardPop.OnKeyPressed.KEY_FINISH:
                            //收款
                            pop.dismiss();
                            //检查输入金额是否命中规则
                            String amount=sb.toString();
                            if(DebitHelper.checkInputAmount(amount)){
                                checkBindCreditCard(amount);
                            }
                            //埋点
                            SelfUtils.buriedClickData(Self.Action.app_click_quick_cashier_receivables,
                                    Self.Action.app_click_quick_cashier_receivables_des,
                                    mEnterPageTime,
                                    mCurrentPageId,
                                    mPrePageId);
                            break;
                        case NumberKeyBoardPop.OnKeyPressed.KEY_DELETE:
                            //删除键
                            if(sb.length()>0){
                                sb.deleteCharAt(sb.length()-1);
                            }
                            break;
                        case NumberKeyBoardPop.OnKeyPressed.KEY_ONE:
                            //数字键1
                        case NumberKeyBoardPop.OnKeyPressed.KEY_TWO:
                            //数字键2
                        case NumberKeyBoardPop.OnKeyPressed.KEY_THREE:
                            //数字键3
                        case NumberKeyBoardPop.OnKeyPressed.KEY_FOUR:
                            //数字键4
                        case NumberKeyBoardPop.OnKeyPressed.KEY_FIVE:
                            //数字键5
                        case NumberKeyBoardPop.OnKeyPressed.KEY_SIX:
                            //数字键6
                        case NumberKeyBoardPop.OnKeyPressed.KEY_SEVEN:
                            //数字键7
                        case NumberKeyBoardPop.OnKeyPressed.KEY_EIGHT:
                            //数字键8
                        case NumberKeyBoardPop.OnKeyPressed.KEY_NINE:
                            //数字键9
                            String str=sb.toString();
                            if(str.contains(".")){
                                //精确到小数点后两位
                                int index=str.indexOf('.');
                                if(str.length()-index-1<2){
                                    sb.append(key);
                                }
                            }else{
                                sb.append(key);
                            }
                            break;
                        case NumberKeyBoardPop.OnKeyPressed.KEY_ZERO:
                            //数字键0
                            String text=sb.toString();
                            //精确到小数点后2位
                            if(text.length()>0){
                                if(text.contains(".")){
                                    int index=text.indexOf('.');
                                    if(text.length()-index-1<2){
                                        sb.append(key);
                                    }
                                }else{
                                    if(!text.startsWith("0")){
                                        sb.append(key);
                                    }
                                }
                            }
                            break;
                        case NumberKeyBoardPop.OnKeyPressed.KEY_DOT:
                            //小数点
                            if(!sb.toString().contains(".")){
                                if(sb.length()!=0){
                                    sb.append(".");
                                }
                            }
                            break;
                    }
                    //限制输入字符数
                    if(sb.length()>8){
                        etAmount.setText(sb.substring(0,8));
                    }else{
                        etAmount.setText(sb.toString());
                    }
                    changePreViewValue(sb.toString());
                    try{
                        etAmount.setSelection(etAmount.getText().length());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });
        }
        if(!pop.isShowing()){
            pop.showAtLocation(etAmount, Gravity.BOTTOM,0,0);
        }
    }

    DebitHelper.CalculateBean calculateBean;

    private void changePreViewValue(String amount){
        String format="%.2f";
        calculateBean= DebitHelper.calculateFee(amount,
                rate.getDiscount(),
                rate.getRate(),
                rate.getEach_charge());
        tvFee.setText(String.format(Locale.CHINESE,format,calculateBean.getFee())+"元");
        tvAmountMoney.setText(String.format(Locale.CHINESE,format,calculateBean.getSpace())+"元");
    }


    private void quickDebitOrder(final String cardId,final String cardLogo,
                                 final String cardName,final String tailNo){
        //下单
        showProgressDialog(false);
        Api.quickDebitOrder(String.valueOf(mApplication.getUser().getID()),
                String.valueOf(calculateBean.getAmount()),
                String.valueOf(calculateBean.getSpace()),
                cardId).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                QuickDebitOrderResult result=JsonUtil.json2Object(s,QuickDebitOrderResult.class);
                if(result.getCode()==Constant.SUC_CODE){
                    QuickDebitOrder summary=result.getData();
                    if(summary!=null&&!TextUtils.isEmpty(summary.getOrder_no())){
                        //成功下单
                        Intent intent=new Intent(QuickDebitActivity.this,QuickDebitShowActivity.class);
                        intent.putExtra(QuickDebitShowActivity.ORDER_NO_S,summary.getOrder_no());
                        intent.putExtra(QuickDebitShowActivity.NAME_S,summary.getUser_name());
                        intent.putExtra(QuickDebitShowActivity.MOBILE_S,summary.getMobile_no());
                        intent.putExtra(QuickDebitShowActivity.AMOUNT_D,calculateBean.getAmount());
                        intent.putExtra(QuickDebitShowActivity.CARD_LOGO_S,cardLogo);
                        intent.putExtra(QuickDebitShowActivity.CARD_NAME_S,cardName);
                        intent.putExtra(QuickDebitShowActivity.CARD_TAIL_NUMBER_S,tailNo);
                        intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(intent);
                        finish();
                    }
                }else{
                    ToastUtil.showToast(result.getMsg());
                }
            }
        });
    }

    private ListPop chooseCardPop;
    private void showChooseCardPop(final List<CreditLimitQuotaAdapter.TypeCreditCard> data) {
        Context context = QuickDebitActivity.this;
        final CreditLimitQuotaAdapter adapter =
                new CreditLimitQuotaAdapter(context, data,
                        Double.parseDouble(etAmount.getText().toString().trim()));
        final AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                chooseCardPop.dismiss();
                CreditLimitQuotaAdapter.TypeCreditCard typeData=data.get(position);
                int type=typeData.getType();
                if(type==CreditLimitQuotaAdapter.TYPE_ADD_CARD){
                    //添加信用卡
                    //获取用户实名信息
                    loadUserRealInfo();
                }else if(type==CreditLimitQuotaAdapter.TYPE_ITEM_NORMAL){
                    if(adapter.canSelect(position)){
                        adapter.setSelected(position);
                        //下单
                        UserBindCards.CreditCard card=typeData.getCard();
                        String cardNumber=card.getCredit_card_no();
                        quickDebitOrder(card.getId(),
                                card.getPicture(),
                                card.getCredit_card_name(),
                                cardNumber.substring(cardNumber.length()-4));
                    }
                }
            }
        };
        chooseCardPop = new ListPop(QuickDebitActivity.this) {
            @Override
            public void configListView(ListView listView) {
                listView.setAdapter(adapter);
                listView.setOnItemClickListener(listener);
            }
        };
        chooseCardPop.setTitle("请选择您的信用卡");
        if (!chooseCardPop.isShowing()) {
            chooseCardPop.showAtLocation(titleBar, Gravity.NO_GRAVITY, 0, 0);
        }
    }


    private void loadUserRealInfo(){
        showProgressDialog(false);
        Api.checkBindCard(String.valueOf(mApplication.getUser().getID())).
                subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissProgressDialog();
                        ToastUtil.showToast(ApplicationHelper.
                                getApplicationContext().
                                getString(R.string.string_request_server_fail));
                    }

                    @Override
                    public void onNext(String s) {
                        dismissProgressDialog();
                        HasBindCardResult result = JsonUtil.json2Object(s, HasBindCardResult.class);
                        if(result.getCode()==1){
                            //已经实名认证，并且绑定了储蓄卡和信用卡
                            RealName realName=result.getData();
                            Intent intent=new Intent(mContext,AddCreditCardActivity.class);
                            intent.putExtra(AddCreditCardActivity.NAME_S,realName.getTrue_name());
                            intent.putExtra(AddCreditCardActivity.ID_CARD_NO_S,realName.getId_card_no());
                            intent.putExtra(AddCreditCardActivity.PAGE_FROM_I,
                                    AddCreditCardActivity.PAGE_QUICK_DEBIT);
                            intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                            startActivity(intent);
                        }else{
                            ToastUtil.showToast(result.getMsg());
                        }
                    }
                });
    }

    @OnClick({R.id.et_amount,R.id.ibt_delete})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.et_amount:
                showPopKeyboard();
                break;
            case R.id.ibt_delete:
                etAmount.setText("");
                break;
        }
    }
}
